package org.yzh.rbac.component;

import org.yzh.rbac.model.vo.Permis;

import java.util.*;

public class PermisUtils {

    public static List<Permis> toTree(Collection<Permis> allNodes) {
        List<Permis> roots = findRoot(allNodes);
        for (Permis root : roots)
            root.setList(findChildren(root, allNodes));
        return roots;
    }

    private static List<Permis> findRoot(Collection<Permis> allNodes) {
        List<Permis> result = new ArrayList<>();
        Iterator<Permis> iterator = allNodes.iterator();
        while (iterator.hasNext()) {
            Permis node = iterator.next();
            if (node.getPid() == 0) {
                result.add(node);
                iterator.remove();
            }
        }
        Collections.sort(result);
        return result;
    }

    private static List<Permis> findChildren(Permis root, Collection<Permis> allNodes) {
        List<Permis> children = new ArrayList<>();

        Integer pid = root.getId();
        Iterator<Permis> iterator = allNodes.iterator();
        while (iterator.hasNext()) {
            Permis node = iterator.next();
            if (pid == node.getPid()) {
                node.setLevel(root.getLevel() + 1);
                children.add(node);
                iterator.remove();
            }
        }

        for (Permis child : children)
            child.setList(findChildren(child, allNodes));

        if (children.isEmpty())
            return null;
        Collections.sort(children);
        return children;
    }
}